﻿using System;
using System.Data;
using System.Globalization;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ZhukBlogLinqExamples.Repositories;

namespace ZhukBlogLinqExamples.FieldTypes.Employee.Controls
{
    public class EmployeeSearch : SimpleQueryControl
    {
        public TableResultControl ResultControl
        {
            get { return (TableResultControl)PickerDialog.ResultControl; }
        }

        public EmployeePicker EditorControl
        {
            get { return (EmployeePicker)PickerDialog.EditorControl; }
        }

        public string RequestedState
        {
            get
            {
                return string.IsNullOrEmpty(Page.Request.QueryString["State"]) 
                    ? "TN" 
                    : Page.Request.QueryString["State"];
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            ColumnList.Visible = false;
        }

        private static DataTable CreateDataTable()
        {
            DataColumn column;
            var table = new DataTable {Locale = CultureInfo.InvariantCulture};
            foreach (string columnName in new[] { "Title", "DepartmentTitle", "PositionTitle" })
            {
                column = new DataColumn {DataType = typeof (string), ColumnName = columnName};
                table.Columns.Add(column);
            }
            var hiddenColumnNames = new [] { "Id" };
            foreach (var columnName in hiddenColumnNames)
            {
                column = new DataColumn
                             {
                                 DataType = typeof (string), 
                                 ColumnName = columnName
                             };
                table.Columns.Add(column);
            }
            return table;
        }

        public override PickerEntity GetEntity(DataRow dataRow)
        {
            if (dataRow == null)
                return null;
            var entity = new PickerEntity
                             {
                                 Key = Convert.ToString(dataRow["Id"]),
                                 DisplayText = Convert.ToString(dataRow["Title"]),
                                 Description = string.Empty,
                                 IsResolved = true
                             };
            entity.EntityData.Clear();
            entity.EntityData.Add("DepartmentTitle", dataRow["DepartmentTitle"]);
            return entity;
        }

        protected override int IssueQuery(string search, string group, int pageIndex, int pageSize)
        {
            search = (search != null) ? search.Trim() : null;
            
            if (string.IsNullOrEmpty(search))
            {
                PickerDialog.ErrorMessage = "Search query is empty";
                return 0;
            }
            var webUrl = SPContext.Current.Web.Url;
            var repository = new EmployeeRepository(webUrl, true);
            var employees = repository.GetEntityCollection();//.SearchEmployees(search, pageIndex-1, pageSize);

            if (employees == null || employees.Count() == 0)
            {
                PickerDialog.ErrorMessage = "There is no result for this query";
                return 0;
            }
            var table = CreateDataTable();

            foreach (var employee in employees)
            {
                var row = table.NewRow();
                row["Id"] = employee.Id ?? 0;
                row["Title"] = employee.Title ?? string.Empty;
                row["DepartmentTitle"] = employee.DepartmentTitle ?? string.Empty;
                row["ManagerTitle"] = employee.ManagerTitle ?? string.Empty;
                row["CellPhone"] = employee.CellPhone ?? string.Empty;
                table.Rows.Add(row);
            }
            PickerDialog.Results = table;
            PickerDialog.ResultControl.PageSize = table.Rows.Count;
            var rc = PickerDialog.ResultControl as TableResultControl;
            if(rc!=null)
            {
                rc.ColumnNames.AddRange(new[] { "Id", "Title", "DepartmentTitle", "ManagerTitle", "CellPhone" });
                rc.ColumnDisplayNames.AddRange(new[] { "ID", "Employee", "Department", "Manager", "CellPhone" });
                rc.ColumnWidths.AddRange(new[] { "5%", "35%", "20%", "25%", "15%" });
            }
            return table.Rows.Count;
        }
    }
}
